package com.leessy.r229;

import android.annotation.SuppressLint;
import android.app.Presentation;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.hardware.display.DisplayManager;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ToastUtils;
import com.leessy.r229.config.Config;
import com.leessy.r229.databinding.ActivityMainBinding;
import com.leessy.r229.utils.DevicesUtil;
import com.leessy.r229.utils.SoundPoolUtil;

import java.lang.reflect.Method;

@SuppressLint("MissingPermission")
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    ActivityMainBinding binding;
    private DevicePolicyManager devicePolicyManager;
    MyPresentation myPresentation;

    @SuppressLint("NewApi")
    @RequiresApi(api = Build.VERSION_CODES.S)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        SoundPoolUtil.init(getApplication());
        binding.version.setText("SN：" + getDeviceSN() + "\n设备名称:" + getDeviceName() + "\n系统版本:" + getSysver());
//        testLockAcquire();
        inittest();
        Intent i = new Intent(Intent.ACTION_RUN);
        i.setClass(this, MService.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startService(i);
        Config.INSTANCE.getAutoReboot();

        DevicesUtil.INSTANCE.setDeviceLog(true);
//        Log.d(TAG, "onCreate: " + MemoryStatus.formatSize(MemoryStatus.getTotalInternalStorageSize()));
//        Log.d(TAG, "onCreate: " + MemoryStatus.formatSize(MemoryStatus.getAvailableInternalMemorySize()));
//        Log.d(TAG, "onCreate: " + MemoryStatus.formatSizeRam(MemoryStatus.getTotalRamSize()));
//        Log.d(TAG, "onCreate: " + MemoryStatus.formatSizeRam(MemoryStatus.getUsedRamSize()));

    }


    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d(TAG, "onConfigurationChanged: ??????????????");
    }

    private void inittest() {
        binding.otaTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: ??????????");
                ToastUtils.showLong("ota点击");
//                OtaUtil.INSTANCE.upgradeOta();
//                OtaUtil.INSTANCE.initFile();
//                AppUtil.INSTANCE.uninstallApp("com.leessy.mdcode");
//                AppUtil.INSTANCE.hideApp("com.hpt.g12factorytest");
//                AppUtil.INSTANCE.unhideApp("com.hpt.g12factorytest");
//                AppUtil.INSTANCE.installApp(new File("sdcard/DMCode_1.2.apk"));
//                InstallSessionUtil2.runInstallSession("sdcard/DMCode_1.2.apk", App.app);
//                InstallSessionUtil.runInstallSession(new File("sdcard/DMCode_1.2.apk"), App.app);

            }
        });

        binding.ota.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            }
        });
//        binding.floatview.setChecked(Config.INSTANCE.getDeviceLock());
        binding.floatview.setChecked(Config.INSTANCE.getDeviceLock());
        binding.floatview.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Config.INSTANCE.setDeviceLock(isChecked);
                MService.Companion.getMService().checkConfig();
            }
        });
        binding.floatview2.setChecked(Config.INSTANCE.getDeviceExpire());
        binding.floatview2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Config.INSTANCE.setDeviceExpire(isChecked);
                MService.Companion.getMService().checkConfig();
            }
        });
        binding.appEnable.setChecked(Config.INSTANCE.getAppEnableCtrl());
        binding.appEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Config.INSTANCE.setAppEnableCtrl(isChecked);
            }
        });
        binding.appInstallCtrl.setChecked(Config.INSTANCE.getInstallationCtrl());
        binding.appInstallCtrl.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Config.INSTANCE.setInstallationCtrl(isChecked);
            }
        });
        binding.showDownloader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MService.Companion.getMService().showDownloader(p++, 0);
            }
        });
        binding.closeDownloader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MService.Companion.getMService().closeDownloader();
            }
        });

        binding.showDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myPresentation != null) return;
                DisplayManager mDisplayManager = (DisplayManager) getSystemService(DISPLAY_SERVICE);
                Display[] displays = mDisplayManager.getDisplays();
                if (displays.length > 1) {
                    //displays[0] 主屏，displays[1] 副屏
                    myPresentation = new MyPresentation(MainActivity.this, displays[1]);
                    myPresentation.show();
                }
            }
        });
        binding.closeDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myPresentation != null) {
                    myPresentation.dismiss();
                    myPresentation = null;
                }
            }
        });

    }

    int p = 0;

    //测试锁屏唤醒
    void testLockAcquire() {
        // 锁屏.
        devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        devicePolicyManager.lockNow();
        new Thread(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }
            // 唤醒屏幕
            PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MyApp:WakeLock");
            wakeLock.acquire();
        }).start();
    }

    public static String getDeviceSN() {
        return getSystemProperties("ro.serialno");
    }

    public static String getSysver() {
        return Build.DISPLAY;
    }

    public String getDeviceName() {
        return Settings.Global.getString(getContentResolver(), Settings.Global.DEVICE_NAME);
    }

    public static String getSystemProperties(String s) {
        String serial = null;
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serial;
    }


    void setStartApp() {
        try {
            Intent it = new Intent("setStartAppPkg");
            it.putExtra("name", "app包名");//包名为””时 取消自启
            sendBroadcast(it);
        } catch (Exception e) {
            Log.d(TAG, "start: err " + e);
        }
    }

    class MyPresentation extends Presentation {
        public MyPresentation(Context outerContext, Display display) {
            super(outerContext, display);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.dialog_normal);//绑定副屏显示的布局

        }
    }


}